package com.offcn.service;

import com.offcn.dao.UserDao;
import com.offcn.dao.UserDaoImpl;
import com.offcn.entity.User;
import com.offcn.utils.PageUtils;

import java.util.List;

public class UserServiceImpl implements UserService {
    UserDao userDao = new UserDaoImpl();

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        return userDao.login(username,password);
    }

    /**
     * 添加数据
     * @param user
     * @return
     */
    @Override
    public boolean add(User user) {
        return userDao.add(user)>0;
    }


    /**
     * 分页
     * @param search
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public PageUtils<User> search(String search, int currentPage, int pageSize) {
        //模糊查询和查询所有
        StringBuffer stringBuffer = new StringBuffer("select * from user where name like ?");
        //获取查询数据的长度
        int total = userDao.search(stringBuffer.toString(), "%" + search + "%").size();
          //分页查询
        stringBuffer.append(" limit ?,?");
        //查询当前页面的数据
        List<User> userList = userDao.search(stringBuffer.toString(), "%" + search + "%", (currentPage - 1) * pageSize, pageSize);
        //把查询到的数据和数据的长度,页量 页码都存入对象中返回给servlet层
        PageUtils pageUtils = new PageUtils(pageSize,currentPage,total,userList);

        return pageUtils;
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @Override
    public boolean update(User user) {
        return userDao.update(user)>0;
    }

    /**
     * 删除用户信息
     * @param uids
     * @return
     */
    @Override
    public boolean del(String[] uids) {
//        如果出现异常就为true  否则为false
        try {
//            遍历数组执行dao层
            for (String uid : uids){
                userDao.del(uid);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
